<!--  -->
<template>
  <div>
    <el-container class="screening-box">
      <el-form
        :inline="true"
        class="form"
        ref="form"
        label-position="right"
        label-width="100px"
      >
        <el-header class="screening-head">
          <div class="title">
            <i class="el-icon-search el-icon--left"></i>筛选查询
          </div>
          <div>
            <span class="toggle" v-show="showScreening" @click="showScreening=!showScreening">
              <i class="el-icon-arrow-up el-icon--left"></i>收起筛选
            </span>
            <span class="toggle" v-show="!showScreening" @click="showScreening=!showScreening">
              <i class="el-icon-arrow-down el-icon--left"></i>展开筛选
            </span>
            <el-button
              class="tlwok-btn"
              type="primary"
              @click="search"
            >查询
            </el-button>
            <el-button class="tlwok-btn" type="primary" plain @click="searchName = ''">重置</el-button>
          </div>
        </el-header>
        <el-main class="screening-body" v-show="showScreening">
          <el-form-item label="项目名：" prop="userName">
            <el-input v-model.trim="searchName" placeholder="请输入项目名"></el-input>
          </el-form-item>
        </el-main>
      </el-form>
    </el-container>
    <div class="table-box">
      <div class="table-title">
        <span class="title">
          <i class="el-icon-notebook-2 el-icon--left"></i>项目列表
        </span>
        <div>
          <el-button
            class="filing-button"
            type="primary"
            icon="el-icon-plus"
            @click="showProjectDialog(false)"
          >添加项目
          </el-button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        border
        :header-cell-style="tableHeaderColor"
        :cell-style="tableCellStyle"
      >
        <el-table-column prop="name" label="项目名称">
          <template slot-scope="scope"><span style="font-weight: bold">{{scope.row.name}}</span></template>
        </el-table-column>
        <el-table-column prop="name" label="设置项目权限">
          <template slot-scope="scope">
            <el-link type="primary" @click="showRoleDialog(scope.row)">项目权限</el-link>
          </template>
        </el-table-column>
        <el-table-column label="关联服务商">
          <template slot-scope="scope">
            <el-link type="primary" @click="showProviderDialog(scope.row)">{{scope.row.isSetUser != 0 ? '查看服务商' :
              '未关联'}}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="设置项目地域">
          <template slot-scope="scope">
            <el-link type="primary" @click="showProjectDialog(scope.row.projectId)">查看地域</el-link>
          </template>
        </el-table-column>
        <el-table-column label="删除">
          <template slot-scope="scope">
            <el-link type="primary" @click="delProject(scope.row.projectId)">删除</el-link>
          </template>
        </el-table-column>

      </el-table>
      <div class="table-handler" v-if="tableData.length>0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.startPage"
          :page-sizes="pageInfo.pageSizeArr"
          :page-size="pageInfo.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
        ></el-pagination>
      </div>
    </div>

    <!--    添加地域-->
    <el-dialog
      :title="projectEditType ? '查看地域' : '新增项目'"
      :visible.sync="projectDialogVisible"
      center
    >
      <el-form
        :validate-on-rule-change="false"
        :inline-message="true"
        ref="userInfoForm"
        class="user-info-form"
        label-width="150px"
      >
        <el-form-item label="项目名称：" prop="name">
          <el-input v-if="projectEditType == false" v-model.trim="projectData.name" placeholder="请输入项目名称"></el-input>
          {{projectEditType? projectData.name :''}}
        </el-form-item>
        <div>
          <div style="margin-bottom: 20px;">项目区域选择：</div>
          <el-container style="height: 400px;">
            <el-main>
              <el-tree
                ref="areaTree"
                :data="areaList"

                show-checkbox
                node-key="code"
                :props="areaDefaultProps">
              </el-tree>
            </el-main>
          </el-container>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="projectToDo"
        >保 存
        </el-button>
        <el-button type="primary" plain @click="projectDialogVisible = false">关 闭</el-button>

      </div>
    </el-dialog>

    <!--    关联服务商-->
    <el-dialog title="关联服务商" :visible.sync="providerDialogVisible" center :fullscreen="true"
               :before-close="closedProvider">
      <div>
        <el-container class="screening-box">
          <el-form
            :inline="true"
            class="form"
            ref="form"
            label-position="right"
            label-width="100px"
          >
            <el-header class="screening-head">
              <div class="title">
                <i class="el-icon-search el-icon--left"></i>筛选查询
              </div>
              <div>
            <span class="toggle" v-show="provider_showScreening"
                  @click="provider_showScreening=!provider_showScreening">
              <i class="el-icon-arrow-up el-icon--left"></i>收起筛选
            </span>
                <span class="toggle" v-show="!provider_showScreening"
                      @click="provider_showScreening=!provider_showScreening">
              <i class="el-icon-arrow-down el-icon--left"></i>展开筛选
            </span>
                <el-button
                  class="tlwok-btn"
                  type="primary"
                  @click="provider_getList"
                >查询
                </el-button>
                <el-button class="tlwok-btn" type="primary" plain @click="provider_searchName = ''">重置</el-button>
              </div>
            </el-header>
            <el-main class="screening-body" v-show="provider_showScreening">
              <el-form-item label="用户名：" prop="userName">
                <el-input v-model.trim="provider_searchName" placeholder="请输入用户名"></el-input>
              </el-form-item>
            </el-main>
          </el-form>
        </el-container>
        <div class="table-box">
          <div class="table-title">
        <span class="title">
          项目名称：{{this.providerData.projectName}}
        </span>
            <div>
              <el-button
                class="filing-button"
                type="primary"
                icon="el-icon-plus"
                @click="showAddUserDialog"
              >新增服务商
              </el-button>
            </div>
          </div>
          <el-table
            ref="multipleTable"
            :data="provider_tableData"
            style="width: 100%"
            border
            :header-cell-style="tableHeaderColor"
            :cell-style="tableCellStyle"
          >
            <el-table-column prop="userName" label="用户名"></el-table-column>
            <el-table-column prop="companyName" label="公司名"></el-table-column>
            <el-table-column prop="userId" label="用户编号"></el-table-column>
            <el-table-column label="添加时间">
              <template slot-scope="scope">{{formatDate(scope.row.createTime)}}</template>
            </el-table-column>
            <el-table-column label="项目信息权限">
              <template slot-scope="scope">{{scope.row.relateProject?'已关联':'-'}}</template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <template>
                  <el-link v-if="scope.row.relateProject" type="primary" @click="provider_related(scope.row, false)">取消项目信息</el-link>
                  <el-link v-else type="primary" @click="provider_related(scope.row, true)">关联项目信息</el-link>
                </template>
                <el-link type="primary" style="margin-left:15px" @click="provider_delUser(scope.row)">删除</el-link>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-handler" v-if="provider_tableData.length>0">
            <el-pagination
              @size-change="provider_handleSizeChange"
              @current-change="provider_handleCurrentChange"
              :current-page="provider_pageInfo.startPage"
              :page-sizes="provider_pageInfo.pageSizeArr"
              :page-size="provider_pageInfo.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="provider_pageInfo.total"
            ></el-pagination>
          </div>
        </div>
      </div>
    </el-dialog>

    <!--添加服务商-->
    <el-dialog title="添加服务商" :visible.sync="providerUserDialogVisible" center>
      <div>
        <el-form :inline="true" ref="form" label-width="5em">
          <el-form-item label="用户名">
            <el-input v-model.trim="providerSearchData.userName" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="公司名称">
            <el-input v-model.trim="providerSearchData.companyName" placeholder="请输入公司名称"></el-input>
          </el-form-item>
          <el-form-item label="用户编号">
            <el-input v-model.trim="providerSearchData.userId" placeholder="请输入用户编号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="tlwok-btn"  type="primary" @click="providerUser_getList">查询</el-button>
          </el-form-item>

        </el-form>
        <!-- <div>
          用户名： <el-input v-model.trim="providerSearchData.userName" placeholder="请输入用户名"></el-input>
          公司名称： <el-input v-model.trim="providerSearchData.companyName" placeholder="请输入公司名称"></el-input>
          用户编号： <el-input v-model.trim="providerSearchData.userId" placeholder="请输入用户编号"></el-input>

        </div> -->

        <div class="table-box">
          <el-table
            ref="multipleTable"
            :data="providerUser_tableData"
            style="width: 100%"
            border
            :header-cell-style="tableHeaderColor"
            :cell-style="tableCellStyle"
            @selection-change="providerUserSelectionChange">
          >
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column prop="userName" label="用户名"></el-table-column>
            <el-table-column prop="companyName" label="公司名"></el-table-column>
            <el-table-column prop="userId" label="用户编号"></el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addProvider">确 定</el-button>
            <el-button @click="providerUserDialogVisible = false">取 消</el-button>

      </span>
    </el-dialog>

    <!--    权限-->
    <el-dialog title="权限设置" :visible.sync="projectRoleDialogVisible" center
               >
      <div>
        <el-form
                :validate-on-rule-change="false"
                :inline-message="true"
                :rules="rules"
                ref="roleForm"
                class="user-info-form"
                label-width="150px"
                :model="prData"
        >
          <el-form-item label="项目名称" >
            {{roleProjectName}}
          </el-form-item>
          <el-form-item label="项目权限" prop="userRoleIdList">
            <el-checkbox-group v-model="prData.userRoleGroupIdList">
              <el-checkbox v-for="(item , i) in roleGroupList"
                           :key="item.id"
                           :label="item.id">{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <span style="color:red">注意：项目信息权限若取消，关联的服务商一并取消项目信息权限</span>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="projectRoleDialogVisible = false">取 消</el-button>
        <el-button
                type="primary"
                @click="toUpdateRoleGroup"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import md5 from 'js-md5'

export default {
  name: 'Project_list',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    // 这里存放数据
    return {
      tableData: [],
      pageInfo: {
        total: 0,
        pageSizeArr: [10, 20, 30, 40],
        size: 10, // 分页页面数量大小
        startPage: 1, // 开始页码
      },
      searchName: '',
      showScreening: true,

      projectDialogVisible: false,
      areaList: [],
      areaDefaultProps: {
        children: 'childrenList',
        label: 'name',
      },
      projectData: {
        id: 0,
        name: '',
        areaList: [],
      },
      projectEditType: false,

      providerDialogVisible: false,
      providerList: [],
      providerData: {
        projectName: '',
        projectId: 0,
      },

      provider_tableData: [],
      provider_pageInfo: {
        total: 0,
        pageSizeArr: [10, 20, 30, 40],
        size: 10, // 分页页面数量大小
        startPage: 1, // 开始页码
      },
      provider_searchName: '',
      provider_showScreening: true,

      providerUserDialogVisible: false,
      providerUser_tableData: [],
      providerSearchData: {
        userId: '',
        userName: '',
        companyName: '',
      },
      providerUserSelectedItem: [],

      /// ////权限
      roleGroupList: [],

      projectRoleDialogVisible: false,
      prData: {
        projectId: 0,
        userRoleGroupIdList: [],
      },
      rules: {

        userRoleGroupIdList: [
          { required: true, message: '请选择权限', trigger: 'blur' },
        ],
      },
      roleProjectName: '',

    }
  },

  mounted () {
    this.getList()
    this.getAreaTree()
    this.getAllRole()
  },
  // 方法集合
  methods: {
    toUpdateRoleGroup () {
      this.$axios.post(
        '/api/manage/role/bindProjectRole',
        { projectId: this.prData.projectId, userRoleIdList: this.prData.userRoleGroupIdList },
      )
        .then(res => {
          if (res.success) {
            this.$message.success('操作成功')
            this.projectRoleDialogVisible = false
          } else {
            this.$message.error(res.desc)
          }
        })
    },

    getAllRole () {
      this.$axios.get(
        '/api/manage/role/getAllUserRole',
      )
        .then(res => {
          if (res.success) {
            this.roleGroupList = res.result
          } else {
            this.$message.error(res.desc)
            this.$router.back()
          }
        })
    },
    showRoleDialog (item) {
      this.$axios.post(
        '/api/manage/role/getProjectRole', { projectId: item.projectId },
      )
        .then(res => {
          if (res.success) {
            const ids = []
            res.result.forEach(item => {
              ids.push(item.id)
            })
            console.log('item', item)
            this.roleProjectName = item.name
            this.prData = {
              projectId: item.projectId,
              userRoleGroupIdList: ids,
            }
            this.projectRoleDialogVisible = true
          } else {
            this.$message.error(res.desc)
          }
        })
    },
    showProviderDialog (item) {
      this.providerData.projectId = item.projectId
      this.providerData.projectName = item.name
      this.providerUserSelectedItem = []
      this.provider_search()
      this.providerDialogVisible = true
    },
    providerUserSelectionChange (val) {
      this.providerUserSelectedItem = this.copyObject(val)
    },
    getAreaTree () {
      this.$axios.get(
        '/api/manage/area/getTree',
      )
        .then(res => {
          if (res.success) {
            this.areaList = res.result
          } else this.$message.error(res.desc)
        })
    },
    delProject (id) {
      this.$confirm('确定删除项目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (id) {
          this.$axios.post(
            '/api/manage/project/del',
                            `id=${id}`,
          ).then(res => {
            if (res.success) {
              this.$message.success('删除成功')
              this.search()
            } else this.$message.error(res.desc)
          })
        } else {
          this.$message.error('管理员ID错误')
        }
      })
    },
    projectToDo () {
      // 获取所选的CHECK

      this.projectData.areaList = this.copyObject(this.$refs.areaTree.getCheckedKeys(true))
      if (this.projectEditType) {
        // 修改
        this.$axios.post(
          '/api/manage/project/update',
          { projectId: this.projectData.id, areaCodeList: this.projectData.areaList },
        )
          .then(res => {
            if (res.success) {
              this.$message.success('保存成功')
              this.projectDialogVisible = false
            } else this.$message.error(res.desc)
          })
      } else {
        // 添加
        if (this.projectData.name && this.projectData.name.length > 0) {
          this.$axios.post(
            '/api/manage/project/add',
            { name: this.projectData.name, areaCodeList: this.projectData.areaList },
          )
            .then(res => {
              if (res.success) {
                this.getList()
                this.$message.success('添加成功')
                this.projectDialogVisible = false
              } else this.$message.error(res.desc)
            })
        } else {
          this.$message.error('请填写项目名称')
        }
      }
    },
    showProjectDialog (id) {
      this.projectEditType = !!id
      if (this.projectEditType) {
        this.projectData.id = id
        this.$axios.post(
          '/api/manage/project/getInfo',
                        `id=${id}`,
        )
          .then(res => {
            if (res.success) {
              this.projectData.name = res.result.name
              this.projectDialogVisible = true
              setTimeout(() => {
                this.$refs.areaTree.setCheckedKeys(res.result.areaCodeList)
              }, 200)
            } else this.$message.error(res.desc)
          })
      } else {
        this.projectData.name = ''
        this.projectData.areaList = []
        this.projectDialogVisible = true
        setTimeout(() => {
          this.$refs.areaTree.setCheckedKeys([])
        }, 200)
      }
    },

    showAddUserDialog () {
      this.providerUser_getList()
      this.providerUserDialogVisible = true
    },

    closedProvider (done) {
      this.getList()
      done()
    },

    addProvider () {
      const userIdList = []
      if (this.providerUserSelectedItem.length <= 0) {
        this.$message.error('请选择服务商')
        return
      }
      this.providerUserSelectedItem.forEach(item => {
        userIdList.push(item.userId)
      })
      this.$axios.post(
        '/api/manage/project/addUser',
        { projectId: this.providerData.projectId, userIdList: userIdList },
      )
        .then(res => {
          if (res.success) {
            this.$message.success('添加成功')
            this.providerUserDialogVisible = false
            this.provider_search()
          } else this.$message.error(res.desc)
        })
    },
    provider_search: function () {
      this.provider_pageInfo = {
        total: 0,
        pageSizeArr: [10, 20, 30, 40],
        size: 10, // 分页页面数量大小
        startPage: 1, // 开始页码
      }
      this.provider_getList()
    },

    provider_delUser (item) {
      const id = item.userId
      this.$confirm(`是否删除项目名称为【${this.providerData.projectName}】 的服务商 【${item.userName}】？`, '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (id) {
          this.$axios.post(
            '/api/manage/project/delUser',
                            `projectId=${this.providerData.projectId}&userId=${id}`,
          ).then(res => {
            if (res.success) {
              this.$message.success('删除成功')
              this.provider_getList()
            } else this.$message.error(res.desc)
          })
        } else {
          this.$message.error('管理员ID错误')
        }
      })
    },

    providerUser_getList: function () {
      this.$axios.post(
        '/api/manage/project/getUserInfoListLikeProjectArea',
                    `userName=${this.providerSearchData.userName}&userId=${this.providerSearchData.userId}&companyName=${this.providerSearchData.companyName}&projectId=${this.providerData.projectId}`,
      )
        .then(res => {
          if (res.success) {
            this.providerUser_tableData = res.result
          } else this.$message.error(res.desc)
        })
    },

    provider_getList: function () {
      this.$axios.post(
                    `/api/manage/project/getProviderList?size=${this.provider_pageInfo.size}&startPage=${this.provider_pageInfo.startPage}`,
                    `name=${this.provider_searchName}&projectId=${this.providerData.projectId}`,
      )
        .then(res => {
          if (res.success) {
            this.provider_pageInfo.total = res.result.total
            this.provider_pageInfo.size = res.result.pageSize
            this.provider_tableData = res.result.list
          } else this.$message.error(res.desc)
        })
    },
    // 分页数量大小设置
    provider_handleSizeChange (val) {
      this.provider_pageInfo.size = val
      this.provider_pageInfo.startPage = 1
      this.provider_getList()
    },
    // 分页当前页设置
    provider_handleCurrentChange (val) {
      this.provider_pageInfo.startPage = val
      this.provider_getList()
    },

    search: function () {
      this.pageInfo = {
        total: 0,
        pageSizeArr: [10, 20, 30, 40],
        size: 10, // 分页页面数量大小
        startPage: 1, // 开始页码
      }
      this.getList()
    },
    getList: function () {
      this.$axios.post(
                    `/api/manage/project/getList?size=${this.pageInfo.size}&startPage=${this.pageInfo.startPage}`,
                    'name=' + this.searchName,
      )
        .then(res => {
          if (res.success) {
            this.pageInfo.total = res.result.total
            this.pageInfo.size = res.result.pageSize
            this.tableData = res.result.list
          } else this.$message.error(res.desc)
        })
    },
    // 分页数量大小设置
    handleSizeChange (val) {
      this.pageInfo.size = val
      this.pageInfo.startPage = 1
      this.getList()
    },
    // 分页当前页设置
    handleCurrentChange (val) {
      this.pageInfo.startPage = val
      this.getList()
    },
    // 修改table header的背景色
    tableHeaderColor ({ row, column, rowIndex, columnIndex }) {
      return 'background-color: #f5f5f5;color: #333;font-weight: bold;text-align:center'
    },
    // 修改table tr行的样式
    tableCellStyle ({ row, column, rowIndex, columnIndex }) {
      return 'text-align:center'
    },

    // 是否关联项目信息 flag:true 关联；flag:false 取消
    provider_related (item, flag) {
      let obj = { url:'', msg:'' };
      if (flag) obj.url = '/api/manage/projectInfo/relatedProjectInfo'
      else {
        obj.url = '/api/manage/projectInfo/cancelRelatedProjectInfo'
        obj.msg = '取消'
      }
      const userId = item.userId
      this.$confirm(`是否${obj.msg}关联项目信息？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (userId) {
          this.$axios.get(
            obj.url + `?userId=${userId}&projectId=${this.providerData.projectId}`
          ).then(res => {
            if (res.success) {
              this.$message.success(`${obj.msg}关联成功`)
              this.provider_getList()
            } else this.$message.error(res.desc)
          })
        } else {
          this.$message.error('管理员ID错误')
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
  .title {
    font-weight: bold;
  }

  .grey {
    color: #bbb;
  }

  .red {
    color: red;
  }

  .screening-box {
    border: 1px solid #ddd;

    .form {
      width: 100%;
    }
  }

  .screening-head {
    background: #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .toggle {
      cursor: pointer;
      margin-right: 50px;
    }
  }

  .screening-body {
    border-top: 1px solid #ddd;
  }

  .btn-box {
    margin-top: 40px;

    .number {
      color: red;
    }

    .el-button--primary {
      .number {
        color: #fff;
      }
    }
  }

  .table-title {
    height: 47px;
    line-height: 47px;
    padding: 0 15px;
    background-color: #f5f5f5;
    border-bottom: 1px solid #ddd;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .filing-button {
      margin-left: 30px;
    }
  }

  .table-box {
    border: 1px solid #ddd;
    margin-top: 30px;

    .el-tag {
      margin: 2px;
      cursor: default;
    }
  }

  .table-handler {
    padding: 5px 15px;
    text-align: right;

    .check-all {
      margin-right: 20px;
    }
  }

  .hasEdit {
    position: absolute;
    top: 0;
    left: 0;

    &::before {
      content: '';
      display: block;
      width: 0;
      height: 0;
      border-top: 30px solid red;
      border-right: 30px solid transparent;
    }

    .text {
      position: absolute;
      top: -3px;
      left: 2px;
      color: #fff;
      font-size: 12px;
    }
  }

  .user-info-form {
    .el-select,
    .el-input {
      width: 300px;
    }

    .tags {
      width: 450px;
    }

    .el-tag {
      cursor: pointer;
      margin-right: 15px;
    }
  }

  .tags-dialog {
    .el-tag {
      margin-right: 15px;
      margin-bottom: 15px;

      &:last-child {
        margin-right: 30px;
      }
    }

    .button-new-tag {
      margin-bottom: 15px;
      height: 32px;
      line-height: 30px;
      padding-top: 0;
      padding-bottom: 0;
      color: #5aa3e5;
      border-color: #bddaf5;
      background: #eff6fc;

      &:focus,
      &:hover {
        color: #fff;
        background: #5aa3e5;
        border-color: #5aa3e5;
      }
    }

    .input-new-tag {
      width: 90px;
      margin-bottom: 15px;
      vertical-align: bottom;
    }
  }

  .upload-box {
    display: inline-block;
  }
</style>
<style>
  .input-new-tag .el-input__inner:focus {
    border-color: #bddaf5;
  }

  .el-tree-node > .el-tree-node__children .el-tree-node {
    width: 33%;
  }

  .el-tree-node.is-expanded > .el-tree-node__children {
    display: flex;
    flex-wrap: wrap;
  }

  .el-tree-node__label {
    padding-left: 5px;
  }
</style>
